import {View, StyleSheet, Text, Image, ScrollView, TouchableOpacity, Alert, FlatList, ActivityIndicator, RefreshControl} from 'react-native';
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {SearchBar, Flex, Provider} from '@ant-design/react-native';
import {getProjectListByOwner} from '~/api/home';
import VCard from '~/components/v-card';
import ZsCard from '~/components/zs-card';
import {getParkingRentList} from '~/api/parking';
import HCard from '~/components/h-card';
import Homeleaseale from '~/components/zs-card/Homeleaseale';
import {getHttpUrl} from '~/api/basic';
let pagecount = 0;
let index = 1;
let size = 10;
const mapGetter = (state) => {
    return {
        userinfo: state.userinfo,
        system: state.system,
    };
};
class SearchHome extends Component {
    static navigationOptions = ({navigation}) => {
        return {
            title: navigation.state.params.listtype === 1 ? '楼盘列表' : navigation.state.params.listtype === 2 ? '租车列表' : '售车列表',
        };
    };
    constructor(props) {
        super(props);
        this.state = {
            CityID: this.props.navigation.getParam('CityID'),
            CityName: this.props.navigation.getParam('CityName'),
            keyword: this.props.navigation.getParam('keyword') || '',
            list: [],
            rentlist: [],
            listtype: this.props.navigation.getParam('listtype'), //1活动列表   2租列表   3售车列表
            page_index: 1,
            page_size: 10,
            isLoading: false, //加载
            refreshing: false,
            footer: 0, //上拉底部显示
            baseurl: '',
        };
        getHttpUrl().then((r) => {
            if (r.code === 0) {
                this.setState({
                    baseurl: r.data,
                });
            }
        });
        this.getList(this.state.keyword);
    }

    onGoCityPage = () => {
        this.props.navigation.navigate('City', {
            updateCityName: (CityName, CityID) => {
                this.setState(
                    {
                        CityName,
                        CityID,
                    },
                    () => {
                        this.getList(this.state.keyword);
                    },
                );
            },
        });
    };

    getList = (keyword) => {
        if (this.state.listtype === 1) {
            //活动列表
            this.getProjectList(keyword);
        } else {
            //租售车位
            this.getParkingRent(keyword);
        }
    };
    //活动列表
    getProjectList(keyword) {
        getProjectListByOwner({
            cityId: this.state.CityID,
            page_index: this.state.page_index,
            page_size: this.state.page_size,
            condidate: {
                buildingName: keyword || '',
            },
        }).then((r) => {
            if (r.code === 0) {
                this.setState({
                    list: r.data.page_data.list,
                    footer: 0,
                });
                if (this.state.page_index === 1) {
                    pagecount = r.data.page_data.total_page_count;
                    this.setState({
                        footer: r.data.page_data.total_item_count < 10 ? 2 : 0,
                    });
                }
            } else {
                console.log(r);
            }
        });
    }
    //租售车位列表
    getParkingRent(keyword) {
        getParkingRentList({
            page_index: this.state.page_index,
            page_size: this.state.page_size,
            condidate: {
                puCityID: this.state.CityID,
                rentType: this.state.listtype === 2 ? 0 : this.state.listtype === 3 ? 1 : 0, //0出租 1出售
                BuildingName: keyword || '',
            },
        }).then((r) => {
            if (r.code === 0) {
                this.setState({
                    rentlist: r.data.list,
                    footer: 0,
                });
                if (this.state.page_index === 1) {
                    pagecount = r.data.total_page_count;
                    this.setState({
                        footer: r.data.total_item_count < 10 ? 2 : 0,
                    });
                }
            } else {
                Alert.alert(r.msg);
            }
        });
    }

    onSearch = (keyword) => {
        keyword = keyword.replace(/\s+/g, '');
        this.setState(
            {
                keyword: keyword,
            },
            () => {
                this.getList(keyword);
            },
        );
    };
    _onRefresh() {
        this.setState({footer: 0, page_index: index, page_size: size}, () => {
            this.getList(this.state.keyword);
        });
    }
    // reloadData = () => {
    //     this.setState({
    //         page_index: index,
    //         page_size: size,
    //         footer: 0,
    //     });
    //     this.getList(this.state.keyword);
    // };

    //上拉加载更多
    loadData = () => {
        this.setState({isLoading: false});
        let dataArray = [];
        if (pagecount - 1 > 0) {
            pagecount = pagecount - 1;
            this.setState(
                {
                    page_index: this.state.page_index + 1,
                    footer: 1,
                },
                () => {
                    if (this.state.listtype == 1) {
                        getProjectListByOwner({
                            cityId: this.state.CityID,
                            page_index: this.state.page_index,
                            page_size: this.state.page_size,
                            condidate: {
                                buildingName: this.state.keyword || '',
                            },
                        }).then((r) => {
                            if (r.code === 0) {
                                dataArray = r.data.page_data.list;
                                dataArray = this.state.list.concat(dataArray);
                                this.setState({
                                    list: dataArray,
                                    isLoading: false,
                                });
                            } else {
                                console.log(r);
                            }
                        });
                    } else {
                        getParkingRentList({
                            page_index: this.state.page_index,
                            page_size: this.state.page_size,
                            condidate: {
                                puCityID: this.state.CityID,
                                rentType: this.state.listtype === 2 ? 0 : this.state.listtype === 3 ? 1 : 0, //0出租 1出售
                                BuildingName: this.state.keyword || '',
                            },
                        }).then((r) => {
                            if (r.code === 0) {
                                dataArray = r.data.list;
                                dataArray = this.state.rentlist.concat(dataArray);
                                this.setState({
                                    rentlist: dataArray,
                                    isLoading: false,
                                });
                            } else {
                                Alert.alert(r.msg);
                            }
                        });
                    }
                },
            );
        } else {
            this.setState({
                footer: 2,
            });
        }
    };

    //上拉底部显示
    genIndicator() {
        if (this.state.footer === 1) {
            return (
                <View style={styles.indicatorContainer}>
                    <ActivityIndicator style={styles.indicator} size={'large'} animating={true} />
                    <Text style={{textAlign: 'center'}}>正在加载更多</Text>
                </View>
            );
        } else if (this.state.footer === 2) {
            return (
                <View
                    style={{
                        height: 30,
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                    }}>
                    <Text
                        style={{
                            color: '#999999',
                            fontSize: 14,
                            marginTop: 5,
                            marginBottom: 5,
                        }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if (this.state.footer === 0) {
            return (
                <View
                    style={{
                        height: 30,
                        alignItems: 'center',
                        justifyContent: 'flex-start',
                    }}>
                    <Text
                        style={{
                            color: '#999999',
                            fontSize: 14,
                            marginTop: 5,
                            marginBottom: 5,
                        }}>
                        上拉加载更多
                    </Text>
                </View>
            );
        }
    }
    _renderItem(data) {
        return (
            <View style={{width: '100%'}}>
                {this.state.listtype === 1 ? (
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            this.props.navigation.push('CommunityInfo', {
                                params: data.item.ProjectDataID,
                            });
                        }}>
                        <VCard item={data.item} baseurl={this.state.baseurl} />
                    </TouchableOpacity>
                ) : (
                    <TouchableOpacity
                        activeOpacity={1}
                        onPress={() => {
                            this.props.userinfo.token === ''
                                ? this.props.navigation.push('Login')
                                : this.props.navigation.push('ParkRentInfo', {
                                      params: data.item.ParkingRentID,
                                  });
                        }}>
                        <ZsCard item={data.item} />
                    </TouchableOpacity>
                )}
            </View>
        );
    }
    _HeaderView = () => {
        return (
            <Flex>
                <Flex onPress={this.onGoCityPage} style={{width: '20%', paddingLeft: '5%'}} numberOfLines={1}>
                    <Text style={{width: '80%'}} numberOfLines={1}>
                        {this.state.CityName}
                    </Text>
                    <Image
                        style={{
                            width: 10,
                            height: 11,
                        }}
                        source={require('~/assets/shouye/dizhi_12x.png')}
                    />
                </Flex>
                <View style={styles.header}>
                    <SearchBar
                        placeholder="搜索..."
                        placeholderTextColor="gray"
                        value={this.state.keyword}
                        style={styles.searchBar}
                        styles={searchBarItem}
                        onChange={this.onSearch}
                    />
                </View>
            </Flex>
        );
    };
    render() {
        return (
            <View style={{flex: 1}}>
                <FlatList
                    data={this.state.listtype === 1 ? this.state.list : this.state.rentlist}
                    style={{width: '100%'}}
                    showsVerticalScrollIndicator={false}
                    renderItem={(data) => this._renderItem(data)}
                    keyExtractor={(item, index) => index}
                    ListHeaderComponent={this._HeaderView}
                    ListFooterComponent={() => this.genIndicator()} //上拉加载更多视图
                    onEndReached={() => {
                        this.loadData();
                    }}
                    onEndReachedThreshold={0.1} // 这个属性的意思是 当滑动到距离列表内容底部不足 0.1*列表内容高度时触发onEndReached函数 为啥要加这个属性 因为不加的话滑动一点点就会立即触发onReached函数，看不到菊花加载中
                    refreshing={true}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={() => {
                                this._onRefresh();
                            }}
                        />
                    }
                />
            </View>
        );
    }
}

export default connect(mapGetter)(SearchHome);

const searchBarItem = {
    wrapper: {backgroundColor: 'transparent'},
    search: {color: 'gray', marginLeft: 7},
    cancelTextContainer: {display: 'none'},
};

const styles = StyleSheet.create({
    header: {
        width: '78%',
        backgroundColor: '#f5f5f500',
    },
    searchBar: {
        backgroundColor: 'white',
        color: '#000',
        borderWidth: 0,
        borderRadius: 17,
        height: 28,
        fontSize: 13,
        marginTop: 3,
    },
    scrollview: {
        flex: 1,
        backgroundColor: '#F0F2F5',
    },
    imagessuccess: {
        width: '100%',
        height: 250,
    },
    image: {
        width: 165,
        height: 62,
        marginTop: 15,
    },
    laba: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        width: '90%',
        marginLeft: '5%',
        marginTop: 15,
        height: 34,
        backgroundColor: '#FFFFFF',
        borderRadius: 5,
    },
    flzuche: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
        paddingLeft: '5%',
    },
    flgengduo: {
        fontSize: 12,
        color: '#999999',
        paddingRight: '5%',
    },
    list: {
        width: '92%',
        margin: '4%',
        flexDirection: 'column',
    },
    item: {
        width: '100%',
    },
    lowername: {
        fontSize: 15,
        color: '#333333',
        fontWeight: 'bold',
    },
    itemtextview: {
        flexDirection: 'column',
        marginLeft: 17,
    },

    text: {
        fontSize: 12,
        color: '#666666',
        marginTop: 9,
    },
    biaoqian: {
        marginTop: 14,
        width: 40,
        height: 20,
        fontSize: 10,
        borderRadius: 2,
        textAlign: 'center',
        paddingTop: 2,
        backgroundColor: '#EB5A31',
        color: '#FFFFFF',
    },
    money: {
        marginTop: 14,
        fontSize: 14,
        marginLeft: 12,
        color: '#EB5A31',
    },
    tjtext: {
        fontSize: 8,
    },
});
